import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

//通过这个代码往数据库中插入一行操作
public class Demo1 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学号:");
        int id = scanner.nextInt();
        System.out.println("请输入姓名:");
        String name = scanner.next();
        //1.先创建一个数据源datasource
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java109?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");
        //2.建立和数据库服务器之间的连接，连接好了以后，才能进行后续的请求-响应交互。
            Connection connection = dataSource.getConnection();
            //3.构造sql
            //String sql = "insert into student values("+ id +",'" + name +"')";
            //String sql = "delete from student where id = 1";
            //String sql = "update student set name = '张三' where id = 2";
            String sql = "insert into student values(?,?) ";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1,id);
            statement.setString(2,name);
            //4.把sql发给服务器
            int n = statement.executeUpdate();
            System.out.println("n = " + n);
            statement.close();
            connection.close();
        //5.执行完毕，关闭连接，释放资源


    }
}
